package cn.big.bigd.biocode.controller;


import cn.big.bigd.biocode.dao.OrganizationDAO;
import cn.big.bigd.biocode.dao.ToolDAO;
import cn.big.bigd.biocode.dao.VisitTrackDAO;
import cn.big.bigd.biocode.service.ToolService;
import cn.big.bigd.biocode.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: BasicController
 * @Description: TODO
 * @Author: FanWang
 * @CreateDate: 2018/1/24 下午3:06
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018/1/24
 **/
@Controller
@RequestMapping("/")
public class BasicController implements ErrorController {


    @Autowired
    private UserService userService;

    @Autowired
    private ToolService toolService;
    @Autowired
    private ToolDAO toolDAO;
    @Autowired
    private OrganizationDAO organizationDAO;

    @Autowired
    private VisitTrackDAO visitTrackDAO;
    @Autowired
    private ErrorAttributes errorAttributes;

    private static final String ERROR_PATH = "/error";

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

    @RequestMapping(ERROR_PATH)
    public String error(HttpServletRequest request, Model model) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        Map map = errorAttributes.getErrorAttributes(requestAttributes, true);


        model.addAttribute("errors", map.values());

        return "error";
    }



    @RequestMapping("login")
    public String login() {
        return  "redirect:index";
    }

    @RequestMapping(value = {"", "index"})
    public String home(Model model) {
        long userCount = userService.count();

        model.addAttribute("userCount",userCount);
        model.addAttribute("toolCount",toolDAO.count());
        model.addAttribute("organizationCount",organizationDAO.count());
        model.addAttribute("downloadCount",visitTrackDAO.downloadCount());
        List<Map<String, Object>> releasesLatest = toolService.findLatestTools();
        model.addAttribute("releases",releasesLatest);
        List<Map<String, Object>> popularTools = toolService.findPopularTools();
        model.addAttribute("popularTools",popularTools);

        return "index";
    }



    @RequestMapping("help")
    public String help() {
        return "help";
    }



}
